package cn.agiledata.bank.barcodepayment.logic;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;

import cn.agiledata.bank.barcodepayment.exception.BarCodePayException;
import cn.agiledata.bank.common.util.DateUtil;
/**
 * 涓婃捣绉诲姩鍏徃鏀惰垂鏉″舰鐮�
 * 
 * @author tangwei
 * 
 */
public class CmccBarCode extends AbstractBarCode {
    /**
     * 鏉″舰鐮佸�鐨勯暱搴�
     */
    private static final int CODE_SIZE = 30;

    public BigDecimal getAmount() {
        return getAmount(19, 28);
    }

    public Date getDate() {
        String ds = getValue().substring(14,18);
        Calendar c = Calendar.getInstance();
        int year = c.get(Calendar.YEAR);
        String dateValue = (year / 100) + ds;
        return DateUtil.string2Date(dateValue, "yyyyMM");
    }
    protected void validate(String barCodeValue) throws BarCodePayException {
        super.validate(barCodeValue);
        if (barCodeValue.length() != CODE_SIZE) {
            throw BarCodePayException.ERROR_BARCODE_LENGTH;
        }
        String b28 = barCodeValue.substring(0,28);
        int e2 = Integer.valueOf(barCodeValue.substring(28,30)).intValue();
        int sum = 0;
        for (int i = 1; i <= b28.length(); i++) {
            sum += intOf(barCodeValue, i);
        }
        if (sum != e2){
            throw BarCodePayException.ERROR_BARCODE;
        }
        Date d = getDate();
        Calendar codeDate = Calendar.getInstance();
        codeDate.setTime(d);
        int codeYear = codeDate.get(Calendar.YEAR);
        Calendar now = Calendar.getInstance();
        int nowYear = now.get(Calendar.YEAR);
        if (codeYear > nowYear && codeYear < nowYear-1) {
            throw BarCodePayException.ERROR_BARCODE;
        }
    }
}
